package StudyCode.summary.mycollection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ConvertVariousDataStructureAsArray {
	public static void main(String[] argv) {
		Collection collection = java.util.Arrays.asList("科技与人文",
				"www.tah1986.com");
		System.out.println(java.util.Arrays.toString(asArray(collection)));
	}

	@SuppressWarnings("unchecked")
	public static <E> E[] asArray(final Collection<? extends E> collection) {
		return collection.toArray((E[]) new Object[collection.size()]);
	}

	@SuppressWarnings("unchecked")
	public static <E> E[] asArray(final Object... array) {
		final E[] elements = (E[]) new Object[array.length];
		for (int i = 0; i < array.length; i++) {
			elements[i] = (E) array[i];
		}
		return elements;
	}

	public static <E> List<E> asList(
			@SuppressWarnings("unchecked") final E... array) {
		List<E> list = new ArrayList<>(array.length);
		for (E element : array) {
			list.add(element);
		}
		return list;
	}

	public static <E> List<E> asList(final Iterator<? extends E> iterator) {
		List<E> list = new ArrayList<>();
		while (iterator.hasNext()) {
			list.add(iterator.next());
		}
		return list;
	}

	public static <E> String toString(Iterator<E> iterator) {
		if (iterator == null || !iterator.hasNext()) {
			return "[]";
		}
		StringBuilder builder = new StringBuilder();
		builder.append('[');
		while (iterator.hasNext()) {
			builder.append(iterator.next()).append(',').append(' ');
		}
		return builder.append(']').toString();
	}
}
